/*
 *  Licensed to the Apache Software Foundation (ASF) under one or more
 *  contributor license agreements.  See the NOTICE file distributed with
 *  this work for additional information regarding copyright ownership.
 *  The ASF licenses this file to You under the Apache License, Version 2.0
 *  (the "License"); you may not use this file except in compliance with
 *  the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

package org.apache.wikimark.container;

import java.io.File;
import java.io.IOException;
import java.io.Reader;
import java.net.URL;
import java.util.Collections;
import java.util.Enumeration;

import javax.servlet.Servlet;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;

import org.apache.wikimark.Connectivity;
import org.apache.wikimark.ScriptServletProvider;
import org.apache.wikimark.http.AbstractPostRequest;

/**
 * The connectivity using {@link Servlet} 
 * 
 * @author Sergey I. Salishev
 */
public class DirectConnectivity implements Connectivity {		
	
	final HttpSessionImpl session = new HttpSessionImpl();
	
	private Servlet servlet;
	private final ScriptServletProvider servletProvider;

	private URL url;
	
	/**
	 * Default constructor for reflection
	 */
	public DirectConnectivity() {
		this(null);
	}
	
	/**
	 * @param servletClass the class of the servlet request processor
	 */
	public DirectConnectivity(Class<? extends Servlet> servletClass) {
		servletProvider = new ScriptServletProvider(servletClass);
	}
	
	@SuppressWarnings("deprecation")
	private Servlet prepareServlet(URL url) {
		final File servletPath = new File(url.getPath());
		final Servlet inst = servletProvider.createServlet(servletPath);
		if (inst instanceof javax.servlet.SingleThreadModel) {
			throw new IllegalArgumentException("SingleThreadModel not supported");
		}
		try {
			inst.init(new ServletConfig() {

				public String getInitParameter(String arg0) {
					return null;
				}

				@SuppressWarnings("unchecked")
				public Enumeration getInitParameterNames() {
					return Collections.enumeration(Collections.EMPTY_LIST);
				}

				public ServletContext getServletContext() {
					return new ServletContextImpl(servletPath.getParent());
				}

				public String getServletName() {
					return inst.toString();
				}
				
			});
		} catch (ServletException e) {
			throw new RuntimeException(e);
		}
		return inst;

	}

	public void setBaseURL(URL url) {
		this.url = url; 
		servlet = prepareServlet(url);
	}

	public void close() throws IOException {
		servlet.destroy();
	}

	public Reader requestPage(AbstractPostRequest request) throws IOException {
		HttpServletResponseImpl result = new HttpServletResponseImpl();
		try {
			servlet.service(new HttpServletRequestImpl(session, url, request),
					result);
		} catch (ServletException e) {
			throw new RuntimeException(e);
		}
		result.getWriter().close();
		result.getOutputStream().close();
		session.update(result);		
		return result.getReader();
	}
	
}
